/*
 * Created on 05-nov-2004
 *
 */
package guru.mercurio.core;


import guru.mercurio.common.Status;
import guru.mercurio.data.ChannelDataManager;
import guru.mercurio.data.DataManager;
import guru.mercurio.data.PassportDataManager;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;



/**
 * @author cobach
 *
 */
public class PassportManager {
    private PassportDataManager pdm;
    private ChannelDataManager cdm;
    private DataManager dm;
    
	public PassportManager(String driver, String dbmsURL, String username, String password) throws Exception{
	    dm=new DataManager(driver,  dbmsURL,  username,  password);
	    pdm=new PassportDataManager(dm);
	    cdm = new ChannelDataManager(dm);
	}
    
    public PassportManager(DataManager dm)  throws Exception{
        this.dm=dm;
        pdm=new PassportDataManager(dm);
        cdm = new ChannelDataManager(dm);
    }
	
	//public RelativeApplicationAddress(String passport, String password, )
    
    
	
	public boolean authenticatePassport(String passport, String password) throws Exception{
	    try{
		    return(password.equals(pdm.getPassword(passport)));
	    }
	    catch(ObjectNotFoundException e){
	        return (false);
	    }
	}
	
	public void increasePassportBalance(String passport, long amount) throws Exception{
	    pdm.setBalance(passport,pdm.getBalance(passport)+amount);
    }
    
    
	public int createPassport(String nombre, String password, String descripcion1, String descripcion2,
	String empresa, String codPais, String codArea, String numero, String email, String contacto) throws Exception {
		try {
			if(!pdm.existPassport(nombre)){
				pdm.createPassport(nombre, password, contacto, email, Integer.parseInt(codPais), Integer.parseInt(codArea), Integer.parseInt(numero));
				pdm.setDesc1(nombre, descripcion1);
				pdm.setDesc2(nombre, descripcion2);
				pdm.setContactCompany(nombre, empresa);
				int iden = pdm.getPassportID(nombre);
				pdm.createBalanceAlarm(iden);
				pdm.createCreditAlarm(iden);
				cdm.createChannel(nombre, "22625", nombre, nombre); //OJO: esto es terminacion o interactivo?
			}else{
				return(Status.PASAPORTE_EXISTENTE);
			}
			
	    }
	    catch (Exception ex) {
	    	return(Status.ERROR_INTERNO);
	    }
	    return(Status.EXITO);
		
	}
	
	public String getEmail(String pasaporte){
		String email = "";
		try {
			email = email.concat(pdm.getContactEmail(pasaporte));
	    }
	    catch (Exception ex) {
	    }
	    return email;
	}
	
	public String getPassword(String pasaporte){
		String password = "";
		try {
			password = password.concat(pdm.getPassword(pasaporte));
	    }
	    catch (Exception ex) {
	    }
	    return password;
	}
	
	public int getBalance(String pasaporte){
		int balance = 0;
		try{
			balance = pdm.getBalance(pasaporte);
			
		}catch(Exception e){
			return 0;
		}
		
		return balance;
	}
	
	public int getAlarmSaldo(String pasaporte,  String password, int passportId){
		int alarma = -105;
		try {
			if (!authenticatePassport(pasaporte, password)){
			    return(Status.NO_AUTENTICADO);
			}
			
			alarma = pdm.getBalanceAlarm(passportId);
			
			
	    }
	    catch (Exception ex) {
	    }
	    
	    return alarma;
	}
	
	public int getPassportId(String pasaporte){
		int id = 0;
		try {
			id = pdm.getPassportID(pasaporte);
	    }
	    catch (Exception ex) {
	    }
	    
	    return id;
	}
	
	public int getPassportCredit(String passport){
		int credit = 0;
		try {
			credit = pdm.getCredit(passport);
	    }
	    catch (Exception ex) {
	    }
	    return credit;
	}
	
	public int getAlarmCredit(String passport, String password, int passportId){
		int alarm = -105;
		try{
			if (!authenticatePassport(passport, password)){
			    return(Status.NO_AUTENTICADO);
			}
			
			alarm = pdm.getCreditAlarm(passportId);
			
		}catch(Exception e){
		}
		
		return alarm;
	}
	
	public int getPassportStatus(String pasaporte){
		int status = 0;
		try{
			status = pdm.getStatus(pasaporte);
		}catch(Exception e){
		}
		return status;
	}
	
	
	public void cambiarStatusPassport(String pasaporte, int status){
		try{
			if(status==0){
				pdm.setStatus(pasaporte,1);
			}else{
				pdm.setStatus(pasaporte,0);
			}
		}catch(Exception e){
		}
	}
	
	public boolean getOnTest(String pasaporte){
		boolean onTest = true;
		try{
			onTest = pdm.getOnTest(pasaporte);
		}catch(Exception e){
		}
		
		return onTest;
	}
	
	public void cambiarOnTest(String pasaporte, String onTest){
		try{
			if(onTest.compareTo("true")==0){
				pdm.setOnTest(pasaporte, false);
			}else{
				pdm.setOnTest(pasaporte, true);
			}
		}catch(Exception e){
		}
	}
	
	public boolean getAppStatus(String pasaporte){
		boolean status = true;
		try {
			status = pdm.getAppStatus(pasaporte);
	    }
	    catch (Exception ex) {
	    }
	    return status;
	}
	
	public void cambiarAppStatus(String pasaporte, String status){
		try {
			if(status.compareTo("true")==0){
				pdm.setAppStatus(pasaporte, false);
			}else{
				pdm.setAppStatus(pasaporte, true);
			}
	    }
	    catch (Exception ex) {
	    }
	}
	
	public boolean getReceptionFlow(String pasaporte){
		boolean flow = true;
		try {
			flow = pdm.getReceptionFlow(pasaporte);
	    }
	    catch (Exception ex) {
	    }
	    return flow;
	}
	
	public void cambiarFlujoMensajes(String pasaporte, String flujo){
		try {
			if(flujo.compareTo("true")==0){
				pdm.setReceptionFlow(pasaporte, false);
			}else{
				pdm.setReceptionFlow(pasaporte, true);
			}
	    }
	    catch (Exception ex) {
	    }
	}
	
	
	public String[] getPassportValues (String pasaporte){
		String[] values = new String[9];
		try {
			values[0] = pdm.getPassword(pasaporte);
			values[1] = pdm.getDesc1(pasaporte);
			values[2] = pdm.getDesc2(pasaporte);
			values[3] = pdm.getContactName(pasaporte);
			values[4] = pdm.getContactCompany(pasaporte);
			values[5] = pdm.getContactEmail(pasaporte);
			Integer pais = new Integer(pdm.getContactPhoneCountryCode(pasaporte));
			values[6] = pais.toString();
			Integer ciudad = new Integer(pdm.getContactPhoneAreaCode(pasaporte));
			values[7] = ciudad.toString();
			Integer numero = new Integer(pdm.getContactPhoneNumber(pasaporte));
			values[8] = numero.toString();
	    }
	    catch (Exception ex) {
	    }
	    return values;
	}
	
	public String[] getReceptorValues (String pasaporte){
		String[] values = new String[3];
		try {
			values[0] = pdm.getAppURL(pasaporte);
			values[1] = pdm.getAppKey(pasaporte);
			values[2] = pdm.getAppProtocol(pasaporte);
			}
		catch(Exception e){
			}
			return values;
	}
	
	public void guardarDatosBasicos(String pasaporte, String[] valores){
		try {
			pdm.setPassword(pasaporte, valores[0]);
			pdm.setDesc1(pasaporte, valores[1]);
			pdm.setDesc2(pasaporte, valores[2]);
			pdm.setContactName(pasaporte, valores[3]);
			pdm.setContactCompany(pasaporte, valores[4]);
			pdm.setContactEmail(pasaporte, valores[5]);
			Integer country = new Integer(valores[6]);
			int pais = country.intValue();
			pdm.setContactPhoneCountryCode(pasaporte, pais);
			Integer area = new Integer(valores[7]);
			int ciudad = area.intValue();
			pdm.setContactPhoneAreaCode(pasaporte, ciudad);
			Integer number = new Integer(valores[8]);
			int numero = number.intValue();
			pdm.setContactPhoneNumber(pasaporte, numero);
	    }
	    catch (Exception ex) {
	    }
	}
	
	public void guardarDatosReceptor(String pasaporte, String[] valores){
		try {
			pdm.setAppURL(pasaporte, valores[0]);
			pdm.setAppKey(pasaporte, valores[1]);
			pdm.setAppProtocol(pasaporte, valores[2]);
	    }
	    catch (Exception ex) {
	    }
	}
	
	
	public void guardarAlarmaSaldo(int passport_id, int valor){
		try {
			pdm.setBalanceAlarm(passport_id, valor);
	    }
	    catch (Exception ex) {
	    }
	}
	
	
	public void guardarAlarmaCredito(int passport_id, int valor){
	try {
		pdm.setCreditAlarm(passport_id, valor);
	    }
	catch (Exception ex) {
	}
	}

	
	
	
	
	
	
	
	public int startReception(String passport, String password){
   		try{
			if (!authenticatePassport(passport,password)){
			    return(Status.NO_AUTENTICADO);
			}
			
			if (pdm.getAppStatus(passport)){
		    	return(Status.NO_CONFIGURADO);
			}

			if (pdm.getReceptionFlow(passport)){
				return(Status.RECEPCION_ESTABA_EN_PROCESO);
			}
			
			pdm.setReceptionFlow(passport,true);
			return(Status.EXITO);
		}		
       	catch (Exception e){
       	    return (Status.ERROR_INTERNO);
       	}
	}
	
	
	
	public int stopReception(String passport, String password){
   		try{
			if (!authenticatePassport(passport,password)){
			    return(Status.NO_AUTENTICADO);
			}
			
			if (pdm.getReceptionFlow(passport)){
				return(Status.RECEPCION_NO_ESTABA_EN_PROCESO);
			}
			
			pdm.setReceptionFlow(passport, false);
			return(Status.EXITO);
		}		
       	catch (Exception e){
       	    return (Status.ERROR_INTERNO);
       	}
	}
	
	
	
	public int configureApplication(String passport, String password, String protocol, String url, String key){
		try{
			if (!authenticatePassport(passport,password)){
			    return(Status.NO_AUTENTICADO);
			}

			pdm.setApp(passport, protocol, url, key);
			
			return(Status.EXITO);
		}
		catch (Exception e){
			return(Status.ERROR_INTERNO);
		}
  
	}

	
	
	public int tryApp(String passport, String password){
		int httpCode=0;
  
	    try{
			if (!authenticatePassport(passport,password)){
			    return(Status.NO_AUTENTICADO);
			}
			return(tryApp(passport));
	    }
	    catch(Exception e){
			return(Status.ERROR_INTERNO);	        
	    }
	}
	
	
	
	private int tryApp(String passport){
		int httpCode=0;
  
		try{
		    URL url = new URL(pdm.getAppURL(passport));

		    URLConnection urlConn = url.openConnection();
		    HttpURLConnection http = (HttpURLConnection)urlConn;
		    http.connect();
		    httpCode = http.getResponseCode();
		}
		catch (Exception e){
		    httpCode = 0;
		}

		if (httpCode==200){
		    return(Status.EXITO);
		}
		else{
			System.out.println("Receptor no disponible");
		    return(Status.RECEPTOR_NO_DISPONIBLE);
		}
	}
}
